<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggleDialog" :class="{ active: show }">
      <span class="placeholder" v-if="!fullLocation">{{placeholder}}</span>
      <span class="value" v-else>{{ fullLocation }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="show">
      <div v-if="loading" class="loading"></div>
      <template v-else>
        <span
          @click="cityChoose(item)"
          class="ellipsis"
          v-for="item in currentList"
          :key="item.code"
          >{{ item.name }}</span
        >
      </template>
    </div>
  </div>
</template>

<script>
import { ref, computed, reactive } from "vue";
import { onClickOutside } from "@vueuse/core";
import axios from "axios";
export default {
  name: "City",
  props: {
    fullLocation: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "请选择配送地址",
    },
  },
  setup(props, { emit }) {
    const show = ref(false);
    const loading = ref(false);
    const cityData = ref([]);
    const open = () => {
      show.value = true;
      // 使用城市获取方法
      loading.value = true;
      getCityData().then((data) => {
        cityData.value = data;
        loading.value = false;
      });

      // 每次打开清空值
      for (const key in changeResult) {
        changeResult[key] = "";
      }
    };
    const close = () => {
      show.value = false;
    };
    const toggleDialog = () => {
      show.value ? close() : open();
    };
    const target = ref(null);
    onClickOutside(target, () => close());

    // 获取城市数据部分
    const getCityData = () => {
      return new Promise((resolve, reject) => {
        // 检查是否已经内存缓存，做一次请求即可
        if (window.cityData) {
          resolve(window.cityData);
        } else {
          // 没缓存
          const url =
            "https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json";
          axios
            .get(url)
            .then((res) => {
              // 存到内存里
              window.cityData = res.data;
              resolve(window.cityData);
            })
            .catch((err) => {
              console.error(err);
            });
        }
      });
    };
    // 用来显示当前数据
    const currentList = computed(() => {
      // 默认返回省一级进行展示
      let list = cityData.value;
      if (changeResult.provinceCode) {
        list = list.find(
          (item) => item.code === changeResult.provinceCode
        ).areaList;
      }
      if (changeResult.cityCode) {
        list = list.find(
          (item) => item.code === changeResult.cityCode
        ).areaList;
      }
      return list;
    });

    // 省市区
    const changeResult = reactive({
      provinceCode: "",
      provinceName: "",
      cityCode: "",
      cityName: "",
      areaCode: "",
      areaName: "",
      fullLocation: "",
    });
    // 记录用户点击地区
    const cityChoose = (item) => {
      if (item.level === 0) {
        changeResult.provinceCode = item.code;
        changeResult.provinceName = item.name;
      }
      if (item.level === 1) {
        changeResult.cityCode = item.code;
        changeResult.cityName = item.name;
      }
      if (item.level === 2) {
        changeResult.areaCode = item.code;
        changeResult.areaName = item.name;
        close();
        changeResult.fullLocation = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.areaName}`;
        // 数据的双向绑定，但是由于要将code也要传回后台，所以这里不能单纯的数据双向绑定
        // emit("update:fullLocation", changeResult.fullLocation);
        emit("change", changeResult);
      }
    };
    return {
      show,
      toggleDialog,
      target,
      currentList,
      loading,
      cityChoose,
    };
  },
};
</script>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
    .loading {
      height: 290px;
      width: 100%;
      background: url(~assets/images/loading.gif) no-repeat center;
    }
  }
}
</style>
